package net.cardgame.orcalecard;

import java.io.IOException;

import jp.jma.oraclecard.MyApplication;
import jp.jma.oraclecard.R;
import net.cardgame.oraclecard.animation.AnimationFactory;
import net.cardgame.oraclecard.animation.AnimationFactory.FlipDirection;
import net.cardgame.oraclecard.common.ImageClickable;
import net.cardgame.oraclecard.common.ThreadLoadImage;
import net.cardgame.orcalecard.bean.CardBean;
import net.cardgame.orcalecard.bean.SettingApp;
import net.cardgame.orcalecard.utils.ConstantValue;
import net.cardgame.orcalecard.utils.KeyboardHelper;
import uk.co.senab.bitmapcache.BitmapLruCache;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaPlayer.OnSeekCompleteListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ViewFlipper;

public class ResultActivity extends Activity implements OnClickListener {
	int deckId, number_of_card;
	ImageView img_card1_bg, img_card2_bg, img_card3_bg, img_card4_bg, img_bg,
			btnSaveHistory;
	ViewFlipper fliper1, fliper2, fliper3, fliper4;
	EditText txtQuestion;
	SettingApp setting;
	boolean flag = false;
	CardBean cardBean1, cardBean2, cardBean3, cardBean4;
	ImageClickable img_card1, img_card2, img_card3, img_card4;
	boolean performFlipCard = true;
	String strQuestion;
	MediaPlayer mediaPlayer;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		if (savedInstanceState != null) {
			performFlipCard = false;
			flag = true;
		}
		getData();
		if (number_of_card == 1)
			setContentView(R.layout.result_one_card);
		else
			setContentView(R.layout.result_activity_layout);
		initView();
		loadImageResource();
	}

	void getData() {
		// get bundle
		setting = ConstantValue.getSettingApp(this);
		Bundle bundle = getIntent().getExtras();
		number_of_card = bundle.getInt("number_of_card");
		cardBean1 = bundle.getParcelable("cardBean1");
		cardBean2 = bundle.getParcelable("cardBean2");
		cardBean3 = bundle.getParcelable("cardBean3");
		cardBean4 = bundle.getParcelable("cardBean4");
		deckId = bundle.getInt("deckId");
		strQuestion = bundle.getString("text_input");

	}

	void initView() {
		setupUI(findViewById(R.id.parent));
		findViewById(R.id.btnreplay_result).setOnClickListener(this);
		findViewById(R.id.btn_replace_1_3_result).setOnClickListener(this);
		findViewById(R.id.btn_goto_toppage_result).setOnClickListener(this);
		btnSaveHistory = (ImageView) findViewById(R.id.btn_share_facebook_result);
		btnSaveHistory.setOnClickListener(ResultActivity.this);
		findViewById(R.id.btnsetting_result).setOnClickListener(this);
		img_card1 = (ImageClickable) findViewById(R.id.img_card1_result);
		img_card2 = (ImageClickable) findViewById(R.id.img_card2_result);
		img_card3 = (ImageClickable) findViewById(R.id.img_card3_result);
		img_card4 = (ImageClickable) findViewById(R.id.img_card4_result);
		img_card1_bg = (ImageView) findViewById(R.id.img_card100_result);
		img_card2_bg = (ImageView) findViewById(R.id.img_card200_result);
		img_card3_bg = (ImageView) findViewById(R.id.img_card300_result);
		img_card4_bg = (ImageView) findViewById(R.id.img_card400_result);
		img_bg = (ImageView) findViewById(R.id.bg_result);
		fliper1 = (ViewFlipper) findViewById(R.id.viewFlipper1);
		fliper2 = (ViewFlipper) findViewById(R.id.viewFlipper2);
		fliper3 = (ViewFlipper) findViewById(R.id.viewFlipper3);
		fliper4 = (ViewFlipper) findViewById(R.id.viewFlipper4);
		txtQuestion = (EditText) findViewById(R.id.txtquestion_result);
		if (strQuestion != null)
			txtQuestion.setText(strQuestion);
	}

	/**
	 * Load all image resource
	 */
	void loadImageResource() {
		// Load background image
		if (deckId == 999) {
			img_bg.setImageResource(R.drawable.bg999);
			img_card1_bg.setImageResource(R.drawable.c99900);
			switch (number_of_card) {
			case 3:
				img_card2_bg.setImageResource(R.drawable.c99900);
				img_card3_bg.setImageResource(R.drawable.c99900);
				break;
			case 4:
				img_card2_bg.setImageResource(R.drawable.c99900);
				img_card3_bg.setImageResource(R.drawable.c99900);
				img_card4_bg.setImageResource(R.drawable.c99900);
				break;
			default:
				break;
			}
		} else {
			new ThreadLoadImage(this, handlerLoadImage,
					ConstantValue.getPathBackgroundByDeckId(this, deckId),
					img_bg, 5).start();
			String path = ConstantValue.getPathDeckImage(this, deckId, "d");
			// Load card background (card00)
			new ThreadLoadImage(this, handlerLoadImage,
					ConstantValue.getPathDeckImage(this, deckId, "d"),
					img_card1_bg, 6).start();
		}
		// Load card1,2,3,4
		switch (number_of_card) {
		case 1:
			loadCard1();
			break;
		case 3:
			loadCard1();
			loadCard2();
			loadCard3();
			break;
		case 4:
			loadCard1();
			loadCard2();
			loadCard3();
			loadCard4();
			break;
		default:
			break;
		}
	}

	private Handler handlerLoadImage = new Handler() {
		private boolean finished1 = false, finished2 = false,
				finished3 = false, finished4 = false, finished5 = false,
				finished6 = false;

		public void handleMessage(Message msg) {
			if (msg.obj == null)
				return;
			if (deckId == 999) {
				finished5 = true;
				finished6 = true;
			}
			switch (msg.what) {
			case 1:
				finished1 = true;
				Drawable result1 = ((Drawable) msg.obj);
				Bitmap bitmap1 = ((BitmapDrawable) result1).getBitmap();
				if (!bitmap1.isRecycled())
					img_card1.setImageBitmap(bitmap1);
				fliper1.setDisplayedChild(0);
				break;
			case 2:
				finished2 = true;
				Drawable result2 = ((Drawable) msg.obj);
				Bitmap bitmap2 = ((BitmapDrawable) result2).getBitmap();
				if (!bitmap2.isRecycled())
					img_card2.setImageBitmap(bitmap2);
				fliper2.setDisplayedChild(0);
				break;
			case 3:
				finished3 = true;
				Drawable result3 = ((Drawable) msg.obj);
				Bitmap bitmap3 = ((BitmapDrawable) result3).getBitmap();
				if (!bitmap3.isRecycled())
					img_card3.setImageBitmap(bitmap3);
				fliper3.setDisplayedChild(0);
				break;
			case 4:
				finished4 = true;
				Drawable result4 = ((Drawable) msg.obj);
				Bitmap bitmap4 = ((BitmapDrawable) result4).getBitmap();
				if (!bitmap4.isRecycled())
					img_card4.setImageBitmap(bitmap4);
				fliper4.setDisplayedChild(0);
				break;
			case 5:
				finished5 = true;
				Drawable result5 = ((Drawable) msg.obj);
				Bitmap bitmap5 = ((BitmapDrawable) result5).getBitmap();
				if (!bitmap5.isRecycled())
					img_bg.setImageBitmap(bitmap5);
				break;
			case 6:
				finished6 = true;
				Drawable result6 = ((Drawable) msg.obj);
				Bitmap bitmap6 = ((BitmapDrawable) result6).getBitmap();
				if (!bitmap6.isRecycled()) {
					if (number_of_card == 4) {
						img_card2_bg.setImageBitmap(bitmap6);
						img_card3_bg.setImageBitmap(bitmap6);
						img_card4_bg.setImageBitmap(bitmap6);
					} else if (number_of_card == 3) {
						img_card2_bg.setImageBitmap(bitmap6);
						img_card3_bg.setImageBitmap(bitmap6);
					}
					img_card1_bg.setImageBitmap(bitmap6);
				}
				break;
			default:
				break;
			}
			boolean loadFinished = false;
			if (number_of_card == 1)
				loadFinished = finished1 && finished5 && finished6;
			else if (number_of_card == 3)
				loadFinished = finished1 && finished2 && finished3 && finished5
						&& finished6;
			else if (number_of_card == 4)
				loadFinished = finished1 && finished2 && finished3 && finished4
						&& finished5 && finished6;
			if (loadFinished) {
				// perform Flip card
				if (performFlipCard) {
					if (setting.sound)
						playMusic();
					AnimationFactory.flipTransition(fliper1,
							FlipDirection.RIGHT_LEFT);
					new ThreadFlipCard(1).start();
				} else {
					fliper1.setDisplayedChild(1);
					fliper2.setDisplayedChild(1);
					fliper3.setDisplayedChild(1);
					fliper4.setDisplayedChild(1);
					img_card1.setOnClickListener(ResultActivity.this);
					img_card2.setOnClickListener(ResultActivity.this);
					img_card3.setOnClickListener(ResultActivity.this);
					img_card4.setOnClickListener(ResultActivity.this);
				}
			}

		};
	};

	class ThreadFlipCard extends Thread {
		int what;

		ThreadFlipCard(int what) {
			this.what = what;
		}

		@Override
		public void run() {
			// TODO Auto-generated method stub
			super.run();
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			handlerFlipCard.sendEmptyMessage(what);
		}
	}

	Handler handlerFlipCard = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				img_card1.setOnClickListener(ResultActivity.this);
				img_card1.setBackgroundResource(R.drawable.shadow_card);
				if (number_of_card > 1) {
					if (setting.sound)
						playMusic();
					AnimationFactory.flipTransition(fliper2,
							FlipDirection.RIGHT_LEFT);
					new ThreadFlipCard(2).start();
				} else {
					flag = true;
					if (mediaPlayer != null)
						mediaPlayer.release();
				}
				break;
			case 2:
				img_card2.setOnClickListener(ResultActivity.this);
				img_card2.setBackgroundResource(R.drawable.shadow_card);
				if (setting.sound)
					playMusic();
				AnimationFactory.flipTransition(fliper3,
						FlipDirection.RIGHT_LEFT);
				new ThreadFlipCard(3).start();
				break;
			case 3:
				img_card3.setOnClickListener(ResultActivity.this);
				img_card3.setBackgroundResource(R.drawable.shadow_card);
				if (number_of_card > 3) {
					if (setting.sound)
						playMusic();
					AnimationFactory.flipTransition(fliper4,
							FlipDirection.RIGHT_LEFT);
					new ThreadFlipCard(4).start();
				} else {
					flag = true;
					if (mediaPlayer != null)
						mediaPlayer.release();
				}
				break;
			case 4:
				img_card4.setOnClickListener(ResultActivity.this);
				img_card4.setBackgroundResource(R.drawable.shadow_card);
				flag = true;
				if (mediaPlayer != null)
					mediaPlayer.release();
				break;

			default:
				break;
			}
		};
	};

	void loadCard1() {
		String path = ConstantValue.getPathCardDetail(this, cardBean1.deckId,
				cardBean1.cardId, number_of_card == 1 ? ConstantValue.X2
						: ConstantValue.X3);
		img_card1.setPath(path);
		new ThreadLoadImage(this, handlerLoadImage, path, img_card1, 1).start();
		img_card1_bg.setVisibility(View.VISIBLE);
		img_card1.setVisibility(View.VISIBLE);
		if (cardBean1.isJump)
			findViewById(R.id.img_jump_card1_result)
					.setVisibility(View.VISIBLE);
		if (number_of_card != 1)
			findViewById(R.id.img_title_card1_result).setVisibility(
					View.VISIBLE);
	}

	void loadCard2() {
		String path = ConstantValue.getPathCardDetail(this, cardBean2.deckId,
				cardBean2.cardId, ConstantValue.X3);
		img_card2.setPath(path);
		new ThreadLoadImage(this, handlerLoadImage, path, img_card2, 2).start();
		img_card2_bg.setVisibility(View.VISIBLE);
		img_card2.setVisibility(View.VISIBLE);
		findViewById(R.id.img_title_card2_result).setVisibility(View.VISIBLE);
		if (cardBean2.isJump) {
			findViewById(R.id.img_jump_card2_result)
					.setVisibility(View.VISIBLE);
		}
	}

	void loadCard3() {
		String path = ConstantValue.getPathCardDetail(this, cardBean3.deckId,
				cardBean3.cardId, ConstantValue.X3);
		img_card3.setPath(path);
		new ThreadLoadImage(this, handlerLoadImage, path, img_card3, 3).start();
		img_card3_bg.setVisibility(View.VISIBLE);
		img_card3.setVisibility(View.VISIBLE);
		findViewById(R.id.img_title_card3_result).setVisibility(View.VISIBLE);
		if (cardBean3.isJump)
			findViewById(R.id.img_jump_card3_result)
					.setVisibility(View.VISIBLE);
	}

	void loadCard4() {
		String path = ConstantValue.getPathCardDetail(this, cardBean4.deckId,
				cardBean4.cardId, ConstantValue.X3);
		img_card4.setPath(path);
		new ThreadLoadImage(this, handlerLoadImage, path, img_card4, 4).start();
		img_card4_bg.setVisibility(View.VISIBLE);
		img_card4.setVisibility(View.VISIBLE);
		findViewById(R.id.img_title_card4_result).setVisibility(View.VISIBLE);
		if (cardBean4.isJump)
			findViewById(R.id.img_jump_card4_result)
					.setVisibility(View.VISIBLE);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (!flag)
			return;
		switch (v.getId()) {
		case R.id.img_card1_result:
			flag = false;
			gotoCardDetail(cardBean1);
			break;
		case R.id.img_card2_result:
			flag = false;
			gotoCardDetail(cardBean2);
			break;
		case R.id.img_card3_result:
			flag = false;
			gotoCardDetail(cardBean3);
			break;
		case R.id.img_card4_result:
			flag = false;
			gotoCardDetail(cardBean4);
			break;
		case R.id.btnreplay_result:
			goBack();
			break;
		case R.id.btn_replace_1_3_result:
			// go to card deck activity
			goCardDeck();
			break;
		case R.id.btn_goto_toppage_result:
			clearCacheBefore();
			goToppage();
			break;

		case R.id.btnsetting_result:
			flag = false;
			Intent intent2 = new Intent(this, SettingActiviy.class);
			startActivityForResult(intent2, 0);
			overridePendingTransition(R.anim.slide_in_right,
					R.anim.slide_out_left);
			break;
		case R.id.btn_share_facebook_result:
			flag = false;
			gotoSaveHistory();
			break;
		default:
			break;
		}
	}

	void gotoSaveHistory() {
		Intent intent = new Intent(this, SaveHistoryActivity.class);
		intent.putExtra("number_of_card", number_of_card);
		intent.putExtra("deckId", deckId);
		intent.putExtra("cardBean1", cardBean1);
		intent.putExtra("cardBean2", cardBean2);
		intent.putExtra("cardBean3", cardBean3);
		intent.putExtra("cardBean4", cardBean4);
		intent.putExtra("question", txtQuestion.getText().toString());
		startActivityForResult(intent, ConstantValue.RESULT_ACTIVITY);
		overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
	}

	void gotoCardDetail(CardBean cardBean) {
		Intent intentGotoCardDetail = new Intent(this, CardDetailActivity.class);
		intentGotoCardDetail.putExtra("deckId", cardBean.deckId);
		intentGotoCardDetail.putExtra("cardId", cardBean.cardId);
		startActivityForResult(intentGotoCardDetail,
				ConstantValue.RESULT_ACTIVITY);
		overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
		flag = true;
		setting = ConstantValue.getSettingApp(this);
	}

	public void setupUI(View view) {
		// Set up touch listener for non-text box views to hide keyboard.
		if (!(view instanceof EditText)) {

			view.setOnTouchListener(new OnTouchListener() {

				public boolean onTouch(View v, MotionEvent event) {
					v.requestFocus();
					KeyboardHelper.hideSoftKeyboard(ResultActivity.this);
					return false;
				}
			});
		}

		// If a layout container, iterate over children and seed recursion.
		if (view instanceof ViewGroup) {

			for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {

				View innerView = ((ViewGroup) view).getChildAt(i);

				setupUI(innerView);
			}
		}
	}

	private void playMusic() {
		if (mediaPlayer == null) {
			mediaPlayer = MediaPlayer.create(this, R.raw.se_card_flip);
			mediaPlayer.setOnPreparedListener(new OnPreparedListener() {

				@Override
				public void onPrepared(MediaPlayer mp) {
					// TODO Auto-generated method stub
					mp.start();
				}
			});
		} else {
			mediaPlayer.seekTo(0);
			mediaPlayer.start();
		}

	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		if (mediaPlayer != null) {
			mediaPlayer.release();
		}
		ClearCache();
		super.onDestroy();
	}

	private void ClearCache() {
		BitmapLruCache cache = MyApplication.getInstance().getBitmapCache();
		cache.removeFromMemory(ConstantValue.getPathCardDetail(this,
				cardBean1.deckId, cardBean1.cardId,
				number_of_card == 1 ? ConstantValue.X2 : ConstantValue.X3));
		cache.removeFromMemory(ConstantValue.getPathCardDetail(this,
				cardBean2.deckId, cardBean2.cardId, ConstantValue.X3));
		cache.removeFromMemory(ConstantValue.getPathCardDetail(this,
				cardBean3.deckId, cardBean3.cardId, ConstantValue.X3));
		cache.removeFromMemory(ConstantValue.getPathCardDetail(this,
				cardBean4.deckId, cardBean4.cardId, ConstantValue.X3));
		cache.removeFromMemory(ConstantValue.getPathCardDetail(this,
				cardBean1.deckId, cardBean1.cardId, ConstantValue.X1));
		cache.removeFromMemory(ConstantValue.getPathCardDetail(this,
				cardBean2.deckId, cardBean2.cardId, ConstantValue.X1));
		cache.removeFromMemory(ConstantValue.getPathCardDetail(this,
				cardBean3.deckId, cardBean3.cardId, ConstantValue.X1));
		cache.removeFromMemory(ConstantValue.getPathCardDetail(this,
				cardBean4.deckId, cardBean4.cardId, ConstantValue.X1));

		if (deckId == 999) {
			String backgoundCard1 = ConstantValue.getPathBackgroundByDeckId(
					this, cardBean1.deckId);
			String backgoundCard2 = ConstantValue.getPathBackgroundByDeckId(
					this, cardBean1.deckId);
			String backgoundCard3 = ConstantValue.getPathBackgroundByDeckId(
					this, cardBean1.deckId);
			String backgoundCard4 = ConstantValue.getPathBackgroundByDeckId(
					this, cardBean1.deckId);
			cache.removeFromMemory(backgoundCard1);
			cache.removeFromMemory(backgoundCard2);
			cache.removeFromMemory(backgoundCard3);
			cache.removeFromMemory(backgoundCard4);
		}
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		goBack();
	}

	void goBack() {
		Intent intent = new Intent(this, GetCardActivity.class);
		Bundle bundle = getIntent().getExtras();
		if (number_of_card != 1) {
			number_of_card = setting.adviseCard ? 4 : 3;
			bundle.putInt("number_of_card", number_of_card);
		}
		bundle.remove("cardBean1");
		bundle.remove("cardBean2");
		bundle.remove("cardBean3");
		bundle.remove("cardBean4");
		bundle.remove("text_input");
		intent.putExtras(bundle);
		startActivity(intent);
		overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
		this.finish();
	}

	void goToppage() {
		Intent intent = new Intent(this, TopPageActivity.class);
		startActivity(intent);
		overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
		this.finish();
	}

	void goCardDeck() {
		Intent intent = new Intent(this, CardDeckActivity.class);
		Bundle bundle = getIntent().getExtras();
		bundle.remove("cardBean1");
		bundle.remove("cardBean2");
		bundle.remove("cardBean3");
		bundle.remove("cardBean4");
		bundle.remove("text_input");
		intent.putExtras(bundle);
		startActivity(intent);
		overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
		this.finish();
	}

	private void clearCacheBefore() {
		if (deckId != 999) {
			BitmapLruCache cache = MyApplication.getInstance().getBitmapCache();
			cache.removeFromMemory(ConstantValue.getPathDeckImage(this, deckId,
					"s"));
			cache.removeFromMemory(ConstantValue.getPathDeckImage(this, deckId,
					"p"));
			cache.removeFromMemory(ConstantValue.getPathDeckImage(this, deckId,
					"m"));
			cache.removeFromMemory(ConstantValue.getPathDeckImage(this, deckId,
					"d"));
			cache.removeFromMemory(ConstantValue.getPathBackgroundByDeckId(
					this, deckId));
		}
	}
}
